'use strict';
var https = require("https");
var iconv = require("iconv-lite");
var async = require('async');
const request = require('request');
const fs = require('fs');
const path = require('path');
const bilibiliUrl = "https://api.bilibili.com/x/web-interface/view"
module.exports = function(Article) {
	Article.updateFromBilibili = function(aid, columnId, list, cb) {
		if((!aid)||(!columnId)){
			return cb()
		}
		updateData(aid, columnId, list, cb)

	}

	Article.remoteMethod('updateFromBilibili', {
		accepts: [{
			arg: 'aid',
			type: 'string'
		}, {
			arg: 'columnId',
			type: 'string'
		}, {
			arg: 'list',
			type: 'array'
		}],
		returns: {
			arg: 'data',
			type: 'object'
		},
		description: "获取B站信息。"
	});

	Article.getFromBilibili = function(id, cb) {
		if((!id)){
			return cb()
		}
		getData(id, cb)

	}

	Article.remoteMethod('getFromBilibili', {
		accepts: {
			arg: 'id',
			type: 'string'
		},
		returns: {
			arg: 'data',
			type: 'array'
		},
		description: "获取B站信息。"
	});

	Article.uptokenURL = function(cb) {
		var options = {
			scope: "qianpeng",
			expires: 7200
		};
		var putPolicy = new qiniu.rs.PutPolicy(options);
		var uploadToken = putPolicy.uploadToken(mac);
		console.log(uploadToken)

		cb(null, uploadToken);
	};
	Article.remoteMethod('uptokenURL', {
		accepts: [],
		http: {
			verb: "get"
		},
		returns: {
			arg: 'uptoken',
			type: 'string'
		},
		description: "获取上传token。"
	});


	function updateData(aid, columnId, list, cb) {
		
		var returnList = [];

		
		async.eachSeries(list, function(item, callback) {
		    getByCid(aid, columnId, item,function(object){
				returnList.push(object)
				callback()
			})
		}, function(err){
			console.log("err");
		    console.log(err);
			cb(null,returnList)
		});



	}

	function getByCid(aid, columnId, oneArticle,callback) {
		
		var url = bilibiliUrl + "?aid=" + aid + "&cid=" + oneArticle.cid;
		https.get(url, function(res) {
			var datas = [];
			var size = 0;
			res.on('data', function(data) {
				datas.push(data);
				size += data.length;
				//process.stdout.write(data);
			});
			res.on("end", function() {
				var buff = Buffer.concat(datas, size);
				var result = iconv.decode(buff, "utf8"); //转码
				// var result = buff.toString();//不需要转编码,直接tostring

				var resultObj = JSON.parse(result).data
				console.log(resultObj);
				var content = '<p>' + resultObj.desc + '</p>';
				content +=
					'<p><iframe src="//player.bilibili.com/player.html?aid=' +
					aid + '&cid=' + oneArticle.cid + '&page=' + oneArticle.page +
					'" width="1100px" height="700px" frameborder="no" scrolling="no" allowfullscreen="allowfullscreen"> </iframe></p>';
				var findObj = {
					robot: aid,
					columnId: columnId,
					cid: oneArticle.cid
				}
				var data = {
					robot: aid,
					columnId: columnId,
					cid: oneArticle.cid,
					title: oneArticle.part,
					publishTime: new Date(),
					content: content,
					abstract: resultObj.desc,
					page:oneArticle.page,
					hasEdit: false
				}
				console.log(data)
				Article.upsertWithWhere(findObj, data, function(err, object) {

					callback(object)

				})

			});
		}).on("error", function(err) {
			// Logger.error(err.stack)
			console.log(err)
			// cb(err)
		});
	}


	function getData(id, cb) {
		var url = bilibiliUrl + "?aid=" + id;
		https.get(url, function(res) {
			var datas = [];
			var size = 0;
			res.on('data', function(data) {
				datas.push(data);
				size += data.length;
				//process.stdout.write(data);
			});
			res.on("end", function() {
				var buff = Buffer.concat(datas, size);
				var result = iconv.decode(buff, "utf8"); //转码
				// var result = buff.toString();//不需要转编码,直接tostring
				// console.log(result);
				var resultObj = JSON.parse(result)
				if(resultObj.data&&resultObj.data.pic){
					upload2CDN(resultObj.data.pic, resultObj.data.aid, function(res) {
						if (res) {
							cb(null, JSON.parse(result));
						} else {
							cb(null)
						}
					
					})
				}else{
					cb("error")
				}
				

			});
		}).on("error", function(err) {
			// Logger.error(err.stack)

			cb(err)
		});
	}
};



var qiniu = require("qiniu");
var CONSTANTS = require("../../server/qiniuConf.js") //这个文件需要自己新建
console.log(CONSTANTS)
// var CONSTANTS={
// 	QINIU:{
// 		AK:'七牛的AK',
// 		SK:'七牛的SK',
// 		BUCKET:'七牛的BUCKET'
// 	}
// }
var config = new qiniu.conf.Config();
var mac = new qiniu.auth.digest.Mac(CONSTANTS.QINIU.AK, CONSTANTS.QINIU.SK);
// 空间对应的机房
config.zone = qiniu.zone.Zone_z2;
// 是否使用https域名
//config.useHttpsDomain = true;
// 上传是否使用cdn加速
//config.useCdnDomain = true;
// 获取七牛 token
var formUploader = new qiniu.form_up.FormUploader(config);
var putExtra = new qiniu.form_up.PutExtra();

function getToken() {
	//需要填写你的 Access Key 和 Secret Key
	const accessKey = CONSTANTS.QINIU.AK;
	const secretKey = CONSTANTS.QINIU.SK;
	const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
	const putPolicy = new qiniu.rs.PutPolicy({
		scope: CONSTANTS.QINIU.BUCKET
	});
	const uploadToken = putPolicy.uploadToken(mac);
	return uploadToken;
}

function upload2CDN(url, id, cb) {
	let readableStream = request(url);
	const key = 'cms_' + id + '.jpg';
	const token = getToken();
	return new Promise((resolve, reject) => {
		try {

			formUploader.putStream(
				token,
				key,
				readableStream,
				putExtra,
				(respErr, respBody, respInfo) => {
					if (respErr) {
						console.log(respErr)
						return cb(null);
					}
					if (respInfo.statusCode == 200) {
						console.log(respBody)

						return cb(respBody && respBody.key || key);
					} else {
						console.log(respInfo)
						return cb(null);
					}
				}
			);
		} catch (e) {
			console.log(e)
			return cb(null);
		}
	})
}
